<template>
  <div class="com-container">
    <div class="com-chart" ref="hotRef"></div>
    <span class="iconfont arrLeft" @click="toLeft" :style="comStyle">&#xe6ef;</span>
    <span class="iconfont arrRight" @click="toRight" :style="comStyle">&#xe6ed;</span>
    <span class="categoryName" :style="comStyle">{{cateName}}</span>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getThemeValue } from '../utils/theme_utils'
export default {
  data () {
    return {
      chartInstance: null,
      allData: null,
      // 一级分类的索引
      currentIndex: 0,
      titleFontSize: 0
    }
  },
  // 需要使用一项新的数据，这项数据又依赖于 data结点的某些数据  ===>  计算属性
  computed: {
    // currentIndex 变化了，cateName就会响应式 变化
    cateName () {
      if (!this.allData) return ''
      return this.allData[this.currentIndex].name
    },
    // 控制箭头和一级分类标题的大小
    comStyle () {
      return {
        fontSize: this.titleFontSize + 'px',
        color: getThemeValue(this.theme).titleColor
      }
    },
    ...mapState(['theme'])
  },
  watch: {
    theme () {
      // 图表销毁
      this.chartInstance.dispose()
      // 以新的主题 初始化图表
      this.initChart()
      this.screenAdapter()
      this.updateChart()
    }
  },
  created () {
    this.$socket.registerCallBack('hotData', this.getData)
  },
  mounted () {
    this.initChart()
    // this.getData()
    this.$socket.send({
      action: 'getData',
      socketType: 'hotData',
      chartName: 'hotproduct',
      value: ''
    })
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed () {
    window.removeEventListener('resize', this.screenAdapter)
    this.$socket.unRegisterCallBack('hotData')
  },
  methods: {
    // 初始化
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.hotRef, this.theme)
      const initOption = {
        title: {
          text: '▎热销商品的占比',
          left: 20,
          top: 20
        },
        legend: {
          top: '15%',
          icon: 'circle'
        },
        tooltip: {
          show: true,
          // 自定义提示内容
          formatter: arg => {
            const thirdCategory = arg.data.children
            // 计算所有三级分类的数值总和
            let total = 0
            thirdCategory.forEach(item => {
              total += item.value
            })
            let resStr = ''
            thirdCategory.forEach(item => {
              resStr += ` ${item.name}：${parseInt(item.value / total * 100)}% <br/> `
            })
            return resStr
          }
        },
        series: [
          {
            type: 'pie',
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true
              },
              labelLine: {
                show: false
              }
            }
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },
    // 获取数据
    getData (res) {
      // 获取服务器的数据
      // const { data: res } = await this.$http.get('hotproduct')
      this.allData = res
      console.log(this.allData)
      this.updateChart()
    },
    // 更新图表
    updateChart () {
      // 处理图表所需数据
      const legendData = this.allData[this.currentIndex].children.map(item => item.name)
      const seriesData = this.allData[this.currentIndex].children.map(item => {
        return {
          name: item.name,
          value: item.value,
          // 三级分类的数据  可以在tooltip中的arg 得到这个数据
          children: item.children
        }
      })
      const dataOption = {
        legend: { data: legendData },
        series: [
          {
            data: seriesData
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    },
    // 让图表自适应
    screenAdapter () {
      this.titleFontSize = this.$refs.hotRef.offsetWidth / 100 * 3.6
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontSize
          }
        },
        legend: {
          itemWidth: this.titleFontSize,
          itemHeight: this.titleFontSize,
          itemGap: this.titleFontSize / 2,
          textStyle: {
            fontSize: this.titleFontSize / 2
          }
        },
        series: [
          {
            // 饼图的半径
            radius: this.titleFontSize * 5,
            // 饼图的位置   [x, y]
            center: ['50%', '60%']
          }
        ]
      }
      this.chartInstance.setOption(adapterOption)
      this.chartInstance.resize()
    },
    toLeft () {
      this.currentIndex--
      if (this.currentIndex < 0) {
        this.currentIndex = this.allData.length - 1
      }
      this.updateChart()
    },
    toRight () {
      this.currentIndex++
      if (this.currentIndex > this.allData.length - 1) {
        this.currentIndex = 0
      }
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
.arrLeft {
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #fff;
}
.arrRight {
  position: absolute;
  right: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #fff;
}
.categoryName {
  position: absolute;
  left: 80%;
  bottom: 20px;
  color: #fff;
}
</style>
